﻿using System;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using GMAC.ReportingSystem.Business.Components;
using GMAC.ReportingSystem.Business.Entities;
using FrameworkManapro.Utilities;


namespace GMAC.ReportingSystem.Paginas
{
    public partial class ManagementUsers : Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new UserComponent();
                var user = ReadUser();
                user.MustChangePassword = true;
                user.UserID = bc.Create(user);
                var audit = new FrameworkManapro.Audit.Audit<User>
                {
                    EntityKey = user.UserID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = user,
                    UserId = ((User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully saved.", null);
                popupExtenderMessage.Show();
                this.PagingControl.TotalRecords = Search();
				Search();
                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New user", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The user could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            btnReset.Visible = false;
            Password.Visible = false;
            var bc = new UserComponent();
            try
            {
                var user = ReadUser();
                if (hfUserId.Value.Trim() != string.Empty)
                {
                    user.UserID = int.Parse(hfUserId.Value);
                    var oldUser = bc.GetDetails(user.UserID);
                    bc.Edit(user);
                    var audit = new FrameworkManapro.Audit.Audit<User>
                    {
                        EntityKey = user.UserID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldUser,
                        NewObject = user,
                        UserId = ((User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully saved.", null);
                    popupExtenderMessage.Show();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save user", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The user couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            btnReset.Visible = false;
            Password.Visible = false;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvUsers != null)
            {
                if (grvUsers.SelectedDataKey != null)
                {
                    try
                    {
                        var userId = (int)this.grvUsers.SelectedDataKey.Value;
                        var bc = new UserComponent();
                        var user = bc.GetDetails(userId);
                        hfUserId.Value = userId.ToString();
                        txtIdentity.Text = user.IdentificationNumber.ToString();
                        txtFirstName.Text = user.Name;
                        txtLastName.Text = user.LastName;
                        txtDepartment.Text = user.Department;
                        txtDescription.Text = user.Description;
                        txtEmail.Text = user.Email;
                        txtLogin.Text = user.Login;
                        var hdRoleId = grvUsers.SelectedRow.FindControl("hdRoleId") as HiddenField;
                        if (hdRoleId != null) ddlRole.SelectedValue = hdRoleId.Value;
                        optOptions.SelectedValue = user.Status.ToString();
                        btnSave.Visible = true;
                        btnNew.Visible = false;
                        btnReset.Visible = true;
                        Password.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify user", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the user.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A user must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvUsers.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A user must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new UserComponent();
                if (grvUsers.SelectedDataKey != null)
                {
                    var userId = (int)this.grvUsers.SelectedDataKey.Value;
                    var user = new User { UserID = userId, Role = new Role() };
                    if (grvUsers != null)
                    {
                        var hdRoleId = grvUsers.SelectedRow.FindControl("hdRoleId") as HiddenField;
                        if (hdRoleId != null) user.Role.RoleID = int.Parse(hdRoleId.Value);
                    }
                    var oldUser = bc.GetDetails(user.UserID);
                    bc.Delete(user);
                    var audit = new FrameworkManapro.Audit.Audit<User>
                    {
                        EntityKey = user.UserID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldUser,
                        UserId = ((User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete user", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The user couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            } 
            ClearFields();
        }
        protected void btnReset_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var user = new User();
                int userID = (int)grvUsers.SelectedDataKey.Value;
                string newPass = EncriptarDescencriptar.Cifrar(System.Configuration.ConfigurationSettings.AppSettings["defaultPassword"]);
                Business.Components.UserComponent userBC = new UserComponent();
                var oldObject = userBC.GetDetails(userID);
                var auxUser = oldObject;
                auxUser.Password = newPass;
                auxUser.MustChangePassword = true;
                userBC.ResetPassword(auxUser);
                user = userBC.GetDetails(userID);
                var audit = new FrameworkManapro.Audit.Audit<User>
                {
                    EntityKey = user.UserID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Update,
                    OldObject = oldObject,
                    NewObject = user,
                    UserId = ((User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Password was reset.", null);
                popupExtenderMessage.Show();

            }
            catch (Exception ex)
            {
                System.Exception expro;
                if (ex.InnerException != null)
                    expro = ex.InnerException;
                else
                    expro = ex;
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(expro.Message.ToString(), "Modify user", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred resetting the password.", ex.ToString());
                popupExtenderMessage.Show();

            }

        }
        #endregion

        #region Other Events

        protected void grvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvUsers, "Select$" + e.Row.RowIndex);
                if (bool.Parse((e.Row.FindControl("hfStatus") as HiddenField).Value) == true)
                {
                    e.Row.Cells[5].Text = "Active";
                }
                else
                {
                    e.Row.Cells[5].Text = "Inactive";
                }
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Modified by:  Michelle A. González A.
        /// Date:         04/08/2010
        /// Description:  Added the following instruction:
        ///                 hfUserId.Value = string.Empty;
        /// </summary>
        private void ClearFields()
        {
            txtIdentity.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtDepartment.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtLogin.Text = string.Empty;
            txtIdentitySearch.Text = string.Empty;
            txtLoginSearch.Text = string.Empty;
            txtNameSeach.Text = string.Empty;
            optOptions.SelectedValue = "True";
            hfUserId.Value = string.Empty;

        }
        private void Initialize()
        {
            try
            {
                var role = new RoleComponent();
                ddlRole.DataSource = role.GetList();
                ddlRole.DataTextField = "Name";
                ddlRole.DataValueField = "RoleID";
                ddlRole.DataBind();
                ddlRole.Items.Insert(0, new ListItem("Select...", string.Empty));
                ddlRoleSearch.DataSource = role.GetList();
                ddlRoleSearch.DataTextField = "Name";
                ddlRoleSearch.DataValueField = "RoleID";
                ddlRoleSearch.DataBind();
                ddlRoleSearch.Items.Insert(0, new ListItem("Select...", string.Empty));
                optOptions.SelectedValue = "True";
                btnSave.Visible = false;
                btnNew.Visible = true;
                btnReset.Visible = false;
                Password.Visible = false;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected user?", null);
                this.PagingControl.TotalRecords = Search();
				Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("User");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvUsers.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        private int Search()
        {
            try
            {
                var bc = new UserComponent();
                var userName = txtNameSeach.Text;
                var login = txtLoginSearch.Text;
                int? roleId = null;
                int? identificationNumber = null;
                if (!string.IsNullOrEmpty(ddlRoleSearch.SelectedValue))
                    roleId = int.Parse(ddlRoleSearch.SelectedValue);
                if (!string.IsNullOrEmpty(txtIdentitySearch.Text))
                    identificationNumber = int.Parse(txtIdentitySearch.Text);
                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;


                UserCollection Usercollection = bc.Search(userName, roleId, identificationNumber, login, paging);                 

                grvUsers.DataSource = Usercollection;
                grvUsers.DataBind();
                return Usercollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search user", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return 0;
            }
        }
        private User ReadUser()
        {
            var user = new User
            {
                IdentificationNumber = int.Parse(txtIdentity.Text),
                Name = txtFirstName.Text,
                LastName = txtLastName.Text,
                Department = txtDepartment.Text,
                Description = txtDescription.Text,
                Email = txtEmail.Text,
                Login = txtLogin.Text,
                Password = System.Configuration.ConfigurationManager.AppSettings["defaultPassword"],
                Status = bool.Parse(optOptions.SelectedValue),
                Role = new Role { RoleID = int.Parse(ddlRole.SelectedValue) },
            };
            return user;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
             Search();
        }
        #endregion

        #region Web Methods

        /// <summary>
        /// Modified by:  Michelle A. González A.
        /// Date:         04/08/2010
        /// Description:  The name of the method GetByLogin, was changed to GetByLoginRepeat, with a new parameter.
        /// </summary>
        [WebMethod]
        public static void CheckLogin(string login, string userId)
        {
            var bcUser = new UserComponent();
            var beUser = bcUser.GetByLoginRepeat(login, userId);

            if (beUser != null)
            {
                throw new Exception("The login is already registered");
            }

        }
        #endregion
    }
}
